import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wk_weather/bean/EnventChangeBean.dart';
import 'package:wk_weather/bean/CityInfo.dart';
import 'package:wk_weather/myConfig/dimen_constant.dart';
import 'package:wk_weather/myconfig/ViewState.dart';
import 'package:wk_weather/myconfig/WidgetState.dart';
import 'package:wk_weather/utils/MyLogTool.dart';
import 'package:wk_weather/bloc/weather/weather_bloc.dart';
import 'package:wk_weather/generated/json/mybean/WeatherModel.dart';
import 'package:wk_weather/views/MyApp.dart';
import 'package:wk_weather/views/pages/home/aqi_chart.dart';
import 'package:wk_weather/views/pages/home/day_forecast.dart';
import 'package:wk_weather/views/pages/home/hour_forecast.dart';
import 'package:wk_weather/views/pages/home/LifeIndexView.dart';
import 'package:wk_weather/views/pages/home/RealtimeView.dart';
import 'package:wk_weather/views/pages/home/RealTimeDetailView.dart';
import 'package:wk_weather/views/widget/StateView.dart';


class CityView extends StatefulWidget {
  final CityModel cityModel;

  const CityView({Key key, @required this.cityModel}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _CityViewState() ;
  }
}

// todo 城市页面详情
class _CityViewState extends State<CityView> with AutomaticKeepAliveClientMixin {
  WeatherModelEntity _modelEntity;
  ///  滚动控件 ，用来实现 切换城市候 可以滚动到相同的位置
  ScrollController _controller;
  StreamSubscription _subscription;
  WidgetState _state = WidgetState.loading;

  @override
  void initState() {
    refreshDataFromNet(); //initState
    // 滚动偏移量
    double initValue = 0;
    if (offsetNotifier.value != null) {
      initValue = offsetNotifier.value;
    }

    _controller = ScrollController(initialScrollOffset: initValue);
    _controller.addListener(() {
      offsetNotifier.value = _controller.offset;
    });

    _subscription = eventBus.on<ChangeMainAppBarIndexEvent>().listen((event) {
      if (offsetNotifier.value != null && event.cityFlag == widget.cityModel.cityFlag) {
        // 为了让不同城市切换时 显示的信息位置同步
        _controller.jumpTo(offsetNotifier.value);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<WeatherBloc, WeatherState>(
      listener: (_, state) {
        weatherPrint("城市页面收到事件 state: ${state.runtimeType}");

        if (state is WeatherSuccess) {
          if (state.cityModel.cityFlag == widget.cityModel.cityFlag) {
            setState(() {
              _state = WidgetState.success;
              _modelEntity = state.entity;
            });
          }
        }

        else if (state is WeatherLoading) {
          if (state.cityModel != null && state.cityModel.cityFlag == widget.cityModel.cityFlag &&
              _modelEntity == null) {
            setState(() {
              _state = WidgetState.loading;
            });
          }
        }

        else if (state is WeatherFailed) {
          if (state.cityModel.cityFlag == widget.cityModel.cityFlag &&  _modelEntity == null) {
            setState(() {
              _state = WidgetState.error;
            });
          }
        }
      },
      child: _buildCityContent(),
    );
  }


  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }


  Future<void> refreshDataFromNet() async {
    weatherPrint("开始获取城市的数据 ${widget.cityModel.displayedName}");
    BlocProvider.of<WeatherBloc>(context) .add(FetchWeatherDataEvent(widget.cityModel));
  }

  Widget _buildCityContent() {
    weatherPrint('重绘城市界面 city, state: $_state');

    if (_state == WidgetState.success) {

      return RefreshIndicator(
        onRefresh: () async {
          refreshDataFromNet(); // onRefresh
        },
        child: SingleChildScrollView(
          controller: _controller,
          physics: BouncingScrollPhysics(),
          child: Container(
            padding: EdgeInsets.symmetric(  horizontal: DimenConstant.cardMarginStartEnd),
            child: Column(
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // todo 当前温度
                RealtimeView(entity: _modelEntity, cityModel: widget.cityModel,),
                SizedBox(
                  height: DimenConstant.dayForecastMarginBottom,
                ),
               // 日出
                RealTimeDetailView(entity: _modelEntity,),
                SizedBox(
                  height: DimenConstant.dayForecastMarginBottom,
                ),

                DayForecastView(resultDaily: _modelEntity?.result?.daily, modelEntity: _modelEntity,),
                SizedBox(
                  height: DimenConstant.dayForecastMarginBottom,
                ),

                // 生活指数
                LifeIndexView(
                  modelResultDailyLifeIndex: _modelEntity?.result?.daily?.lifeIndex,
                  skycon: _modelEntity?.result?.realtime?.skycon,
                ),

                SizedBox(
                  height: 30,
                ),
                // 空气质量指数
                AqiChartView(entity: _modelEntity),
                SizedBox(
                  height: DimenConstant.dayForecastMarginBottom,
                ),


                HourForecastView(
                  resultHourly: _modelEntity?.result?.hourly,
                ),
                SizedBox(
                  height: 30,
                ),

                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("数据由“彩云科技” API提供", style: TextStyle(color: Colors.white54),),
                    ],
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
              ],
            ),
          ),
        ),
      );
    }

    else if (_state == WidgetState.error) {
      return StateView(
        weatherState: ViewState.error,
      );
    }

    else {
      return StateView(weatherState: ViewState.loading);
    }
  }


  // get 方法的语法糖 写法， 不习惯
  @override
  bool get wantKeepAlive => true;


}
